#include <iostream>

void testC()
{
    // // 显示类型转换
    // int a = 123;
    // char c = (char)a;
    // printf("%d %c\n", a, c);

    // 隐式类型转换
    double num = 123.456;
    int ans = num;
    printf("num:%f\nans:%d\n", num, ans);
}

class father
{
    virtual void f() {};
};

class son : public father
{
    virtual void f() override {};

public:
    void test()
    {
        std::cout << "void test()" << std::endl;
    }
};

void test_static_cast()
{
    // 1.基本类型的转化
    double num = 123.456;
    int a = static_cast<int>(num);

    // 2.将void*转化为其他指针
    void *p1 = &num;
    int *p2 = static_cast<int *>(p1);

    // 3.支持类的向上转换
    son s;
    father f = static_cast<father>(s);
}

void test_dynamic_cast(father *pf)
{
    // 用于将基类指针/引用强制转化为派生类指针/引用？
    if (son *ps = dynamic_cast<son *>(pf))
    {
        // 执行son特有的函数
        ps->test();
    }
    else
    {
        std::cout << "转换失败，无法转换" << std::endl;
    }
}

void test_const_cast()
{
    volatile const int a = 1;
    // int &b = a;   会报错

    int &b = const_cast<int &>(a);
    b = 2;
    std::cout << "a:" << a << " b:" << b << std::endl;
    printf("a addr:%p\nb addr:%p\n", &a, &b);
}

// 特殊类设计
// 只能在栈中定义
class stackOnly
{
public:
    stackOnly getObject()
    {
        return stackOnly();
    }

private:
    stackOnly() {}
};

// 只能在堆中定义
class headOnly
{
public:
    headOnly *getObjectPtr()
    {
        return new headOnly();
    }

private:
    headOnly() {}
};

int main()
{
    // testC();

    // father *pf = new father();
    // father *ps = new son();
    // test_dynamic_cast(pf);
    // test_dynamic_cast(ps);

    test_const_cast();
}